﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DevExpress.Xpo;
namespace ChuanPlus.DAO
{
    class UserDAO
    {
        /// <summary>
        /// Get user by UserID
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static Users getUserById(int id)
        { 
            XPQuery<Users> users = new XPQuery<Users>(Session.DefaultSession);
            var list = (from u in users
                       where u.UserID == id
                       select u).First();
            return list as Users;
        }
        public static bool IsDuplicate(Users user)
        { 
         XPQuery<Users> users = new XPQuery<Users>(Session.DefaultSession);
            var list = (from u in users
                       where u.Username == user.Username
                       select u).Take(1);
            List<Users> lstUser = new List<Users>(list.AsEnumerable());

            if (lstUser.Count > 0)
            {
                return true;
            }
            return false;
        }

        public static Users Authenticate(string username, string password,ref bool authenticated, ref bool isAdmin)
        {
            XPQuery<Users> users = new XPQuery<Users>(Session.DefaultSession);
            var list = (from u in users
                       where u.Username == username && u.Password == password && u.Active == true
                       select u).Take(1);
            List<Users> lstUser = new List<Users>(list.AsEnumerable());
            
            if(lstUser.Count > 0)
            {
                isAdmin = lstUser[0].Permission;
                authenticated = true;
                return lstUser[0];
            }
            isAdmin = authenticated = false;
            return null;
        }
    }
}
